<template>
    <div class="container">
        <div class="form-container" v-loading="loading" element-loading-text="Logining...">
            <h3 style="align-self: flex-start; color: black; margin: 20px;">Login</h3>
            <el-form :model="formData" label-width="auto" style="max-width: 600px; display: flex; flex-direction: column;">
                <el-form-item label="Account">
                    <el-input v-model="formData.account" />
                </el-form-item>
                <el-form-item label="Password">
                    <el-input v-model="formData.password" show-password type="password"/>
                </el-form-item>
                <el-form-item style="align-self: center; width: 100%;">
                    <el-button type="primary" @click="onSubmit" style="width: 100%;">login</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { api_login } from '../api/apis';
import { ElMessage } from 'element-plus';
import { useGlobalStore } from '../store';
import { useRouter } from 'vue-router';

const loading = ref(false);

const formData = reactive({
    account: '',
    password: ''
})

const router = useRouter();

const onSubmit = async () => {
    try {
        loading.value = true;
        const ret = await api_login(formData.account, formData.password);
        console.log(ret);

        if (ret.status == 200) {
            if (ret.data.errCode == 0) {
                const store = useGlobalStore();
                store.token = ret.data.data.apiToken;
                store.tokenExpired = ret.data.data.expired;

                localStorage.setItem('token', JSON.stringify({
                    token: ret.data.data.apiToken,
                    expired: ret.data.data.expired
                } as any, null, 2));

                router.push('/console/index');
            }else {
                ElMessage.error('Oops, login failed. err: ' + ret.data.errMsg);
            }
        }
    }catch (err: any) {
        console.log(err);
        ElMessage.error('Oops, login exception happened. err: ' + err.message);
    }finally {
        loading.value = false;
    }
}
</script>

<style scoped>
.container {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: cornflowerblue;
}

.form-container {
    width: 300px;
    padding: 20px;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: #eeeeee;
    box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.2);
}
</style>